package com.summer.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.summer.entity.UserInfo;
import com.summer.entity.gongxinbao.tbdata.TbRelativizeResult;
import com.summer.entity.gongxinbao.tbreport.TbReportRelativizeResult;
import com.summer.entity.gongxinbao.zhima.RelData;
import com.summer.entity.gongxinbao.zhima.RelTbZhima;
import com.summer.mapper.UserInfoMapper;
import com.summer.service.ITbRelativizeService;
import com.summer.util.HttpsUtil;
import com.summer.util.SnUtil;
import com.summer.variable.Constant;
import net.sf.json.JSONObject;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 公信宝回调
 */
@Controller
@RequestMapping("/v1.0/api/gongxinbao")
public class GongXinBaoContoller extends BaseController {

    private static Logger LOG = LoggerFactory.getLogger(GongXinBaoContoller.class);
    @Resource
    private ITbRelativizeService tbRelativizeService;
    @Resource
    private UserInfoMapper userInfoMapper;
    private static final String GXB_FETCH_URL = "https://prod.gxb.io/crawler/data/report";
    private static final String GXB_ZHIMA_URL = "https://prod.gxb.io/crawler/data/zmcredit";
    private static final String GXB_TOKEN_URL = "https://prod.gxb" +
            ".io/crawler/auth/v2/get_auth_token";
    private static final String GXB_APP_ID = "gxb613d458f8f912185";
    private static final String GXB_APP_SECRET = "2e1694718cfe452abfb5ea109a4616e2";

    @RequestMapping("/tbCallback")
    public void tbCallback(@RequestBody String jsonBody, HttpServletResponse response) {
        long start = System.currentTimeMillis();
        LOG.info("公信宝tbCallback start");
        HashMap<String, String> resMap = new HashMap<String, String>();
        resMap.put("retCode", "1");
        resMap.put("retMsg", "成功");
        boolean saveFlag = true;
        if (StringUtils.isBlank(jsonBody)) {
            LOG.info("公信宝tbCallback null == jsonBody");
            toObjectJson(response, JSON.toJSONString(resMap));
            return;
        }
        JsonParser parser = new JsonParser();
        JsonObject jsonObject = parser.parse(jsonBody).getAsJsonObject();
        String token = jsonObject.get("token").getAsString();
        String name = jsonObject.get("name").getAsString();
        String phone = jsonObject.get("phone").getAsString();
        try {
            TbRelativizeResult result = tbRelativizeService.getResult(jsonBody);
            tbRelativizeService.save(result);
        } catch (Exception e) {
            LOG.error("公信宝tbRelativizeService getResult error_" + e.getMessage());
        }
        String taoBaoReport = "";
        try {
            taoBaoReport = fetchReport(token, GXB_FETCH_URL);
        } catch (IOException e) {
            LOG.error("公信宝fetchTaoBaoReport error_" + e.getMessage());
            saveFlag = false;
        }
        String zhimaReport = "";
        try {
            zhimaReport = fetchReport(token, GXB_ZHIMA_URL);
        } catch (IOException e) {
            LOG.error("fetchZhimaReport error_" + e.getMessage());
            saveFlag = false;
        }
        RelData relData = null;
        if (StringUtils.isBlank(zhimaReport)) {
            LOG.info("公信宝tbCallback null == zhimaReport");
        } else {
            try {
                relData =
                        tbRelativizeService.getZhimaResult(zhimaReport, name);
                tbRelativizeService.saveZhima(relData);
            } catch (Exception e) {
                LOG.error("公信宝 getZhimaResult error_" + e.getMessage());
            }
        }
        if (StringUtils.isBlank(taoBaoReport)) {
            LOG.info("公信宝tbCallback null == taoBaoReport");
        } else {
            try {
                TbReportRelativizeResult reportResult =
                        tbRelativizeService.getReportResult(taoBaoReport, name);
                tbRelativizeService.saveReportResult(reportResult);
            } catch (Exception e) {
                LOG.error("公信宝getReportResult error_" + e.getMessage());
            }
        }
        if (!saveFlag) {
            resMap.put("retCode", "2");
            resMap.put("retMsg", "失败");
            toObjectJson(response, JSON.toJSONString(resMap));
            return;
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("phone", phone);
        List<UserInfo> userInfoList =
                userInfoMapper.selectSimple(params);
        //修改芝麻分
        if (CollectionUtils.isNotEmpty(userInfoList) && null != relData && CollectionUtils.isNotEmpty(relData.getZmCredits())) {
            UserInfo userInfo = userInfoList.get(0);
            //取最新
            List<RelTbZhima> zmCredits =
                    relData.getZmCredits().stream().sorted(Comparator.comparing(RelTbZhima::getMonth).reversed()).collect(Collectors.toList());
            RelTbZhima relTbZhima = zmCredits.get(0);
            UserInfo newUser = new UserInfo();
            newUser.setId(userInfo.getId());
            newUser.setZmScore(relTbZhima.getZmScore());
            newUser.setZmStatus(Constant.USER_ZM_AUTHENTIC);
            String month = relTbZhima.getMonth();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                Date date = sdf.parse(month);
                newUser.setZmLastTime(date);
            } catch (ParseException e) {
                LOG.error("公信宝getReportResult ParseException error_" + e.getMessage());
            }
            userInfoMapper.updateByPrimaryKeySelective(newUser);
        }
        LOG.info("公信宝tbCallback success，耗时：{} s", (System.currentTimeMillis() - start) / 1000);
        toObjectJson(response, JSON.toJSONString(resMap));
    }

    @ResponseBody
    @RequestMapping(value = "/test", method = {RequestMethod.POST, RequestMethod.GET})
    public Object test() {
        return successMsg("成功", "");
    }

    @ResponseBody
    @RequestMapping(value = "/gxbToken", method = {RequestMethod.POST, RequestMethod.GET})
    public Object gxbToken(String mobilePhone, String sourceH5Code) throws Exception {
        HashMap<String, Object> params = new HashMap<>();
        params.put("phone", mobilePhone);
        List<UserInfo> userInfoList =
                userInfoMapper.selectSimple(params);
        if (CollectionUtils.isEmpty(userInfoList) || StringUtils.isBlank(userInfoList.get(0).getRealName())) {
            return errorMsg("请先补全您的姓名");
        }
        UserInfo userInfo = userInfoList.get(0);
        String idCard = userInfo.getIdCard();
        if (StringUtils.isBlank(idCard)) {
            return errorMsg("请先补全您的身份证信息");
        }

        Map<String, Object> data = new HashMap<String, Object>();
        Map<String, String> map = new HashMap<>();
        String sn = SnUtil.getPaymentSn(mobilePhone, "TB");
        String authItem = "ecommerce";
        map.put("sequenceNo", sn);
        map.put("phone", mobilePhone);
        map.put("authItem", authItem);
        map.put("name", userInfo.getRealName());
        map.put("idcard", idCard);
        map.put("appId", GXB_APP_ID);
        String timestamp = new Date().getTime() + "";
        map.put("timestamp", timestamp);
        String sign = DigestUtils.md5Hex(String.format("%s%s%s%s%s", GXB_APP_ID, GXB_APP_SECRET,
                authItem,
                timestamp,
                sn));
        map.put("sign", sign);

        String content = JSONObject.fromObject(map).toString();
        LOG.info("【gxbToken参数】：" + content);
        String result = HttpsUtil.postJsonData(GXB_TOKEN_URL, content);
        LOG.info("【gxbToken返回参数】：" + result);
        JsonParser parser = new JsonParser();
        String token = "";
        JsonObject jsonObject = parser.parse(result).getAsJsonObject();
        if (jsonObject.has("data")) {
            JsonObject dataJson = jsonObject.get("data").getAsJsonObject();
            if (dataJson.has("token")) {
                token = dataJson.get("token").getAsString();
            }
        }
        data.put("token", token);
        return successMsg("成功", data);
    }

    /**
     * 查询淘宝数据和芝麻报告
     *
     * @param
     * @return
     */
    public String fetchReport(String token, String path) throws IOException {
        long timestamp = System.currentTimeMillis();
        String sign = DigestUtils.md5Hex(String.format("%s%s%s", GXB_APP_ID, GXB_APP_SECRET,
                timestamp));
        StringBuilder sb = new StringBuilder(path);
        sb.append("/").append(token);
        sb.append("?appId=").append(GXB_APP_ID).append("&timestamp=").append(timestamp).append(
                "&sign" +
                        "=").append(sign);
        String url = sb.toString();
        String result = HttpsUtil.doGet(url, null, "utf-8", false);
        return result;
    }


}
